package com.ruoyi.system.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.SysContract;
import com.ruoyi.system.domain.SysContractLabel;
import com.ruoyi.system.domain.SysContractLog;
import com.ruoyi.system.service.ISysContractLogService;
import com.ruoyi.system.service.ISysContractService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.SysContractSpdMapper;
import com.ruoyi.system.domain.SysContractSpd;
import com.ruoyi.system.service.ISysContractSpdService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;

/**
 * 业绩分配Service业务层处理
 *
 * @author ruoyi
 * @date 2025-06-23
 */
@Service
public class SysContractSpdServiceImpl implements ISysContractSpdService
{
    @Autowired
    private SysContractSpdMapper sysContractSpdMapper;

    /** 合同service接口层 */
    @Autowired
    private ISysContractService sysContractService;

    /** 合同日志service 接口层 */
    @Autowired
    private ISysContractLogService sysContractLogService;

    /**
     * 查询业绩分配
     *
     * @param id 业绩分配主键
     * @return 业绩分配
     */
    @Override
    public SysContractSpd selectSysContractSpdById(Long id)
    {
        return sysContractSpdMapper.selectSysContractSpdById(id);
    }

    /**
     * 查询业绩分配列表
     *
     * @param sysContractSpd 业绩分配
     * @return 业绩分配
     */
    @Override
    public List<SysContractSpd> selectSysContractSpdList(SysContractSpd sysContractSpd)
    {
        return sysContractSpdMapper.selectSysContractSpdList(sysContractSpd);
    }

    /**
     * 根据合同主键查询业绩分配
     * @param contractId
     * @return
     */
    @Override
    public List<SysContractSpd> selectSysContractSpdListByContractId(Long contractId) {
        return sysContractSpdMapper.selectSysContractSpdListByContractId(contractId);
    }

    /**
     * 新增业绩分配
     *
     * @param sysContractSpdList 业绩分配
     * @return 结果
     */
    @Override
    @Transactional
    public int insertSysContractSpd(List<SysContractSpd> sysContractSpdList)
    {
        int status = 0;
        try {
            //业绩分配新增判断方法
            emptyInsertSysContractSpd(sysContractSpdList);

            //构建新增业绩分配实体集合
            List<SysContractSpd> insertSysContractSpdList = new ArrayList<>();
            insertSysContractSpdList = buildInsertSysContractSpdList(sysContractSpdList);

            //构建修改业绩分配实体集合
            List<SysContractSpd> updateSysContractSpdList = new ArrayList<>();
            updateSysContractSpdList = buildUpdateSysContractSpdList(sysContractSpdList);

            //业绩分配新增方法
            if (!CollectionUtils.isEmpty(insertSysContractSpdList)){
                status += sysContractSpdMapper.insertSysContractSpdList(insertSysContractSpdList);
            }
            //业绩修改方法
            if (!CollectionUtils.isEmpty(updateSysContractSpdList)){
                for(int i = 0;i < updateSysContractSpdList.size();i++){
                    SysContractSpd sysContractSpd = updateSysContractSpdList.get(i);
                    status += sysContractSpdMapper.updateSysContractSpd(sysContractSpd);
                }
            }

            //构建合同日志
            SysContractLog sysContractLog = sysContractLogService.buildSysContractLog(sysContractSpdList.get(0).getContractId(), "修改业绩分配");

            //新增合同日志
            sysContractLogService.insertSysContractLog(sysContractLog);
        }
        catch (Exception e){
            //事务回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new RuntimeException(e.getMessage());
        }
        return status;
    }

    /**
     * 新增业绩分配判断方法
     * @param sysContractSpdList
     */
    @Override
    public void emptyInsertSysContractSpd(List<SysContractSpd> sysContractSpdList) {
        if (CollectionUtils.isEmpty(sysContractSpdList)){
            throw new RuntimeException("未传输业绩分配信息,请联系管理员");
        }

        //查询合同
        SysContract sysContract = sysContractService.selectSysContractById(sysContractSpdList.get(0).getContractId());
        if (null == sysContract){
            throw new RuntimeException("合同信息不存在，请联系管理员");
        }

        //百分比
        Long percentage = 100L;

        //金额
        BigDecimal contractMoney = sysContract.getContractMoney();

        for (int i = 0;i < sysContractSpdList.size();i++){
            SysContractSpd sysContractSpd = sysContractSpdList.get(i);
            //百分比
            if(null == sysContractSpd.getPercentage()){
                throw new RuntimeException("百分比未传输");
            }
            percentage = percentage - sysContractSpd.getPercentage();
            if (percentage < 0){
                throw new RuntimeException("百分比累加高于100%");
            }
            //金额
            if (null == sysContractSpd.getPrice() || sysContractSpd.getPrice().compareTo(new BigDecimal(0)) == -1){
                throw new RuntimeException("金额不可为空或为0");
            }
            contractMoney = contractMoney.subtract(sysContractSpd.getPrice());
            //判断分配金额是否超过合同金额
            if (contractMoney.compareTo(new BigDecimal(0)) == -1){
                throw new RuntimeException("分配金额累计超过合同金额");
            }
        }
    }

    /**
     * 构建业绩分配实体集合
     * @param sysContractSpdList
     * @return
     */
    @Override
    public List<SysContractSpd> buildInsertSysContractSpdList(List<SysContractSpd> sysContractSpdList) {
        List<SysContractSpd> insertSysContractSpdList = new ArrayList<>();
        sysContractSpdList.forEach(it ->{
            if (null == it.getId()){
                //创建人
                it.setCreateBy("admin");
                //创建时间
                it.setCreateTime(DateUtils.getNowDate());
                insertSysContractSpdList.add(it);
            }
        });
        return insertSysContractSpdList;
    }

    /**
     * 构建业绩分配修改实体集合
     * @param sysContractSpdList
     * @return
     */
    @Override
    public List<SysContractSpd> buildUpdateSysContractSpdList(List<SysContractSpd> sysContractSpdList) {
        List<SysContractSpd> updateSysContractSpdList = new ArrayList<>();
        sysContractSpdList.forEach(it ->{
            if (null != it.getId()){
                //创建人
                it.setUpdateBy("admin");
                //创建时间
                it.setUpdateTime(DateUtils.getNowDate());
                updateSysContractSpdList.add(it);
            }
        });
        return updateSysContractSpdList;
    }

    /**
     * 修改业绩分配
     *
     * @param sysContractSpd 业绩分配
     * @return 结果
     */
    @Override
    public int updateSysContractSpd(SysContractSpd sysContractSpd)
    {
        return sysContractSpdMapper.updateSysContractSpd(sysContractSpd);
    }

    /**
     * 批量删除业绩分配
     *
     * @param ids 需要删除的业绩分配主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteSysContractSpdByIds(Long[] ids)
    {
        int status = 0;
        try {
            //查询业绩分配
            SysContractSpd sysContractSpd = this.selectSysContractSpdById(ids[0]);

            //构建合同日志
            SysContractLog sysContractLog = sysContractLogService.buildSysContractLog(sysContractSpd.getContractId(), "删除业绩分配");

            //新增合同日志
            sysContractLogService.insertSysContractLog(sysContractLog);

            //删除业绩分配方法
            status = sysContractSpdMapper.deleteSysContractSpdByIds(ids);
        }
        catch (Exception e){
            //事务回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new RuntimeException(e.getMessage());
        }
        return status;
    }

    /**
     * 删除业绩分配信息
     *
     * @param id 业绩分配主键
     * @return 结果
     */
    @Override
    public int deleteSysContractSpdById(Long id)
    {
        return sysContractSpdMapper.deleteSysContractSpdById(id);
    }
}